import React, {useContext, useEffect, useState} from "react";
import {
    Alert,
    Dimensions,
    ImageBackground,
    RefreshControl,
    ScrollView,
    Text,
    TouchableOpacity,
    View
} from "react-native";
import LocaleContext from "../libs/locale";
import WalletContext from "../libs/wallet";
// import logo from '../assets/aboutlogo.png';
import topBG from '../assets/redEnvelopeInfo/top.png';
import firstBG from '../assets/redEnvelopeInfo/First.png';
import firstBGEn from '../assets/redEnvelopeInfo/FirstEn.png';
import {getHotTokens, getTxInfo, QueryRedEnvelope} from "../libs/nodes";
import Clipboard from "@react-native-community/clipboard";
import Toast from "react-native-simple-toast";
import {Icon} from "react-native-elements";
import under from "../assets/redEnvelopeLoad/under.png";
import AsyncStorage from "@react-native-async-storage/async-storage";

const {width, height,scale} = Dimensions.get("window");

const RedEnvelopeInfo = ({navigation,route}:any)=>{
    const locale:any = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);
    const [coverTxt,setCoverTxt] = useState('');
    const [num,setNum] = useState('1');
    const [amount,setAmount] = useState('0');
    const [sender,setSender] = useState("")//红包的发送人
    const [number,setNumber] = useState(1)//红包的数量
    const [rmnumber,setRmnumber] = useState(1)//红包的剩余数量
    const [total,setTotal] = useState(1)//红包的数量
    const [members,setMembers]:any = useState([])
    const [refresh, setRefresh] = useState(true);
    const [showTraninfo,setShowTraninfo] = useState(false);
    const [traninfo,settraninfo]:any = useState({});
    const [showFirstBG,setShowFirstBG] = useState(false);
    const [lang,setLang] = useState("en");
    const [coinName,setCoinName] = useState("SAT")
    const [logo,setLogo] = useState(require('../assets/aboutlogo.png'));

    const pkgid = route?.params?.pkgid || "";
    const BGheight = width*0.85*1.6624;

    useEffect(()=>{

        const strToTimestamp = (date:string)=>{
            // date = '2015-03-05 17:59:23';
            var dateTmp = date.replace(/-/g,'/')   //为了兼容IOS，需先将字符串转换为'2018/9/11 9:11:23'
            var res = Date.parse(dateTmp)    //返回'2018-9-12 9:11:23'的时间戳
            // var res =  new Date(date).getTime();
            console.log(res)
            return res;
        }

        function bubbleSort(arr:any) {//冒泡排序
            var len = arr.length;
            for(var i = 0; i < len - 1; i++) {
                for(var j = 0; j < len - 1 - i; j++) {
                    if(strToTimestamp(arr[j].time) < strToTimestamp(arr[j+1].time)) {       // 相邻元素两两对比
                        var temp = arr[j+1];       // 元素交换
                        arr[j+1] = arr[j];
                        arr[j] = temp;
                    }
                }
            }
            return arr;
        }

        async function getTokenImg(conAddress: string) {
            if (conAddress == "") {
                return;
            }
            const ht=await getHotTokens();
            var hotTokens=JSON.parse(JSON.stringify(ht));
            for( let i = 0 ; i < hotTokens.tokens.length ; i++)
            {
                if(conAddress == hotTokens.tokens[i].address)
                {
                    if(hotTokens.tokens[i].url)
                    setLogo({uri:hotTokens.tokens[i].url});
                }
            }

        }

        const work = async () => {
            if(!refresh)
            {
                return ;
            }
            const lang:any = await AsyncStorage.getItem('@lang');
            setLang(lang);

            var res = await QueryRedEnvelope(pkgid);
            try{
                await getTokenImg(res.dict.type);
            }catch (e) {

            }
            setCoinName(res.dict.coinname || "SAT");
            setSender( res.dict.nickname ||res.dict.sender);
            setNumber(res.dict.number);
            setRmnumber(res.dict.rmnumber);
            setTotal(parseFloat(res.dict.total)/100);
            if(res.dict.url)
            {
                setLogo({uri:res.dict.url})
            }
            // console.log("???????"+res.pkgitems[0].amount)
            var pkgitems =bubbleSort(res.pkgitems);

            console.log("排序结果是："+JSON.stringify(pkgitems))
            setMembers(pkgitems);
            setCoverTxt(res.dict.desc);
            setRefresh(false)
            setShowFirstBG(true)
        }

        work();
    },[refresh]);

    const getTranInfo = async (item: any) => {

        var res = {};
        console.log(item.transhash)
        if(item.transhash=="")
        {
            res = {hash:item.transhash,addressIn:"",addressOut:item.getter,amount:item.amount/100,height:0}
            settraninfo(res);
            setShowTraninfo(true);
            return res;
        }
        try {
            res =  await getTxInfo(item.transhash);
            if(res === false)
            {
                res = {hash:item.transhash,addressIn:"",addressOut:item.getter,amount:item.amount/100,height:0};
            }
            settraninfo(res);
            setShowTraninfo(true);
            return res;
        }
        catch (e) {
            res = {hash:item.transhash,addressIn:"",addressOut:item.getter,amount:item.amount/100,height:0}
            settraninfo(res);
            setShowTraninfo(true);
            return res;
        }
    }

    const onCopy = (data:any) => {
        Clipboard.setString(data);
        Toast.show(locale?._('copied') as string);
    };

    const Biggest = (Amount:number)=>{
        for(var i=0;i<members.length;i++)
        {
            if(Amount < parseFloat(members[i].amount))
            {
                return false;
            }
        }
        return true;
    }


    return(
        <View style={{width:width,height:height}}>
           <View style={{width:width,height:height}}>
               <View style={{height:0.03*height,backgroundColor:"rgb(253,52,34)"}} />
               <ImageBackground source={topBG} style={{width:width,height:0.12*height}}/>
               <ImageBackground source={logo} style={{width:0.15*width,height:0.15*width,borderRadius:0.15/2*width,backgroundColor:"white",borderWidth:0,marginTop:-0.075*width,marginLeft:(0.5-0.075)*width}} />
               <Text style={{textAlign:"center",fontSize:width/360*12,marginTop:10}}>{sender}</Text>
               <Text style={{textAlign:"center",fontSize:width/360*20,marginTop:10,paddingLeft:width*0.05,paddingRight:width*0.05}}>{coverTxt}</Text>
               <Text style={{textAlign:"center",fontSize:width/360*20,marginTop:20}}>{(locale as any)._("RedEnvelopeInfo.NumberOf")}：{number-rmnumber}/{number}</Text>
               <View style={{flex:1,backgroundColor:"#fbfaf6",marginTop:10,borderTopWidth:1/scale,borderTopColor:"#ddd"}}>
                   <Text style={{marginLeft:15,marginTop:15,marginBottom:15,fontSize:width/360*13}}>
                       {number}{(locale as any)._("RedEnvelopeInfo.InfoTip")} {total} {coinName}
                   </Text>
                   <ScrollView refreshControl={
                       <RefreshControl refreshing={false} onRefresh={() => setRefresh(true)} collapsable={true}/>
                   }>
                       {
                           members.map((item:any,index:any)=>(
                               <TouchableOpacity onPress={()=>{getTranInfo(item);}}>
                                   <View key={index} style={{width:width,height:66,backgroundColor:"white",borderTopWidth:1/scale,borderTopColor:"#ddd",flexDirection:"row"}}>
                                       <TouchableOpacity style={{flexDirection:"row"}} onPress={() => {
                                           // navigation.navigate("ChatView",{ToAddress:item.getter,desc:item.nickname!==""?item.nickname:(item.getter.slice(0, 3)+"..."+item.getter.slice(-3)),info: []})
                                       }}>
                                           <ImageBackground source={logo} style={{width:width*0.15,height:width*0.15,alignSelf:"center",marginLeft:15}}/>
                                           <View style={{flexDirection:"column"}}>
                                               <View style={{flex:1,justifyContent:"flex-end"}}>
                                                    <Text style={{marginLeft:width/360*10}}>{item.nickname!==""?item.nickname:(item.getter.slice(0, 4)+"..."+item.getter.slice(-4))}</Text>
                                               </View>
                                               <View style={{flex:1,flexDirection:"row",marginLeft:width/360*10,paddingTop:5}}>
                                                   {
                                                       rmnumber==0 && Biggest(item.amount)?
                                                       <View style={{flexDirection:"row"}}>
                                                           <Icon style={{marginTop:width/360*13*0.2}} type={"font-awesome"} name="diamond" color={"#FBCF38"} size={width/360*13}/>
                                                           <Text style={{color:"#FBCF38",fontSize:width/360*15 }}> {locale._("RedEnvelopeInfo.King")}</Text>
                                                       </View>
                                                           :null
                                                   }
                                               </View>
                                           </View>
                                       </TouchableOpacity>
                                       <View style={{flex:1,flexDirection:"column",alignItems:"flex-end"}}>
                                           <View style={{flex:1,marginRight:15,justifyContent:"flex-end"}}>
                                               <Text style={{color:"black",fontSize:width/360*17}}>{parseFloat(item.amount)/100}</Text>
                                           </View>
                                           <View style={{flex:1,marginRight:15}}>
                                               {
                                                   (item.status!=="2")?
                                                       <Text style={{color:"#a9a9a9",fontSize:width/360*12,paddingTop:5}}>{item.time.slice(0,-3)} ({locale._("RedEnvelopeInfo.Waiting")})</Text>
                                                       :
                                                       <Text style={{color:"#a9a9a9",fontSize:width/360*12,paddingTop:5}}>{item.time.slice(0,-3)} ({locale._("RedEnvelopeInfo.Success")})</Text>
                                               }
                                           </View>
                                       </View>
                                   </View>
                               </TouchableOpacity>
                           ))
                       }
                       {
                           members.length===0 && showFirstBG?
                               (
                                   lang=="zh"?
                                   <ImageBackground source={firstBG} style={{width:width*0.6,height:width*93/76*0.6,alignSelf:"center"}}/>
                                   :
                                   <ImageBackground source={firstBGEn} style={{width:width*0.6,height:width*459/396*0.6,alignSelf:"center"}}/>
                               )
                               :null
                       }
                   </ScrollView>

                   <View style={{height:0.08*height,backgroundColor:"white",flexDirection:"row",paddingTop:height*0.015}}>
                       <View style={{flex:1,justifyContent:"flex-end",flexDirection:"row"}}>
                       {
                           <TouchableOpacity onPress={()=>{
                               Alert.alert("",locale._("RedEnvelopeIndex.RedEnvelopeTip1")+"：("+pkgid+")"+"   "+coinName+"\n"+locale._("RedEnvelopeIndex.RedEnvelopeTip2")+":  https://smartxdown.lanzoul.com/b036y4ftc   password:smartx"+"\n"+locale._("RedEnvelopeIndex.RedEnvelopeTip3")+"  https://red.smartx.one/#/?pkgid="+pkgid,[{
                               text: locale?._('ok'),
                               onPress: async () => {
                                   onCopy(locale._("RedEnvelopeIndex.RedEnvelopeTip1")+"：("+pkgid+")"+"   "+coinName+"\n"+locale._("RedEnvelopeIndex.RedEnvelopeTip2")+":  https://smartxdown.lanzoul.com/b036y4ftc   password:smartx"+"\n"+locale._("RedEnvelopeIndex.RedEnvelopeTip3")+" https://red.smartx.one/#/?pkgid="+pkgid);
                               }
                           }])}
                           }>
                               <Text style={{alignSelf:"center",color:"blue",fontSize:width/360*15,marginTop:height*0.005}}>{(locale as any)._("RedEnvelopeInfo.Share")}</Text>
                           </TouchableOpacity>
                       }
                       </View>
                       <Text style={{color:"blue",fontSize:width/360*15,marginTop:height*0.005}}>丨</Text>


                       <View style={{flex:1,justifyContent:"flex-start",flexDirection:"row"}}>
                           <TouchableOpacity onPress={()=>{navigation.navigate('RedEnvelopeList');}}>
                               {
                                   <Text style={{alignSelf:"center",color:"blue",fontSize:width/360*15,marginTop:height*0.005}}>{(locale as any)._("RedEnvelopeInfo.Record")}</Text>
                               }
                           </TouchableOpacity>
                       </View>

                   </View>
                   <View style={{justifyContent:"flex-end",backgroundColor:"white"}}>
                       <Text style={{height:width/360*30,alignSelf:"center",color:"grey",fontSize:width/360*13}}>{(locale as any)._("RedEnvelopeInfo.RedEnvelopeHash")}{pkgid.slice(0, 9)}</Text>
                   </View>
               </View>
           </View>
            {
                showTraninfo?
                    <View style={{marginTop:-height,height:height,width:width,backgroundColor:"#0000009E",alignItems:"center",justifyContent:"center"}}>
                        <View style={{width:0.85*width,height:0.6*height,backgroundColor:"#FB3D2A",borderRadius:20,overflow:"hidden",marginTop:0*height}}>
                            <TouchableOpacity style={{width:0.1*width,height:0.1*width,marginTop:5,alignSelf:"flex-end",marginRight:5}}
                                              onPress={()=>{setShowTraninfo(false)}}>
                                <Text style={{fontSize:width/360*30,color:"#F5FEB0",borderColor:"#E0432D"}}>×</Text>
                            </TouchableOpacity>
                            <ImageBackground source={logo} style={{width:0.17*width,height:0.17*width,alignSelf:"center",marginTop:10}}/>
                            <View >
                                <Text style={{alignSelf:"center",marginTop:15,fontSize:width/360*13,fontWeight:"bold",color:"#FFBCA2"}}> {traninfo.hash!==""?(traninfo.hash.slice(0,15)+"..."+traninfo.hash.slice(-15)):""} </Text>
                                <Text style={{alignSelf:"center",marginTop:8,fontSize:width/360*13,fontWeight:"bold",color:"#FFBCA2"}}> {} </Text>
                                <Text style={{alignSelf:"center",marginTop:15,fontSize:width/360*20,fontWeight:"bold",color:"#FFBCA2",paddingLeft:width*0.05,paddingRight:width*0.05}}>{traninfo.height>0?locale._('RedEnvelopeInfo.TranSuccess'):locale._('RedEnvelopeInfo.TranWaiting')}</Text>
                                {/*    */}
                            </View>
                            <View style={{flex:1,justifyContent:"flex-end"}}>
                                <ImageBackground source={under} style={{width:width*0.85,height:height*0.23}}>
                                    <View style={{flex:1,marginTop:height*0.23*0.35}}>
                                        <View style={{flex:1,justifyContent:"flex-end",alignItems:"center"}}>
                                            <TouchableOpacity onPress={()=>{traninfo.hash!==""?navigation.navigate('WebBrowserInfo',{url:("https://explore.smartx.one/TransactionDetails?hash="+traninfo.hash),showExplore:true}):null}}>
                                                <Text style={{fontSize:width/360*17,backgroundColor:"#C62C1F",padding:4,marginBottom:0.04*height,color:"white",borderRadius:5}}>{locale._('RedEnvelopeInfo.ViewTran')} ></Text>
                                            </TouchableOpacity>
                                        </View>
                                    </View>

                                </ImageBackground>
                            </View>
                        </View>
                    </View>
                    :null
            }

        </View>

    );
}
export  default RedEnvelopeInfo;
